<template>
  <!-- :close-on-click-modal="false" //禁用点击空白区域
  :close-on-press-escape="false" //禁用ESC键 -->
  <el-dialog
    :title="!userId ? '新增' : '修改'"
    :close-on-press-escape="false" 
    :close-on-click-modal="false"
    :append-to-body="true"
    :lock-scroll="true"
    :visible.sync="visible">
    <el-form v-if="userId==0" 
      label-position="right"   label-width="80px"  status-icon :inline="true"  size="mini"
      :model="dataForm" :rules="dataRule" ref="dataForm"  @keydown.enter.native.prevent="dataFormSubmit()"  >
      <el-form-item label="账号" prop="username" >
        <el-input v-model="dataForm.username" placeholder="登录帐号"></el-input>
      </el-form-item>
      <el-form-item label="姓名" prop="name"  >
        <el-input v-model="dataForm.name" placeholder="真实姓名"></el-input>
      </el-form-item>
      <el-form-item  label="密码" prop="password" 
      :class="{ 'is-required': !userId }">
        <el-input class="select" v-model="dataForm.password" type="password" show-password placeholder="密码"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="comfirmPassword" :class="{ 'is-required': !userId }">
        <el-input show-password class="select" v-model="dataForm.comfirmPassword" type="password" placeholder="确认密码"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="dataForm.email" placeholder="邮箱"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="dataForm.phone" placeholder="手机号"></el-input>
      </el-form-item>
      <el-form-item label="院系" prop="department">
        <el-select class="select" v-model="dataForm.department" filterable placeholder="院系">
          <el-option  v-for="item in departmentDict" :label="item.dictLabel" :key="item.id" :value="item.dictLabel"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="身份" size="mini" prop="state">  
        <el-radio-group class="radioGroup" v-model="dataForm.state">
          <el-radio  class="radio" v-for="item in getDictList('role')"  :key="item.dictLabel" :label="parseInt(item.dictValue)">{{ item.dictLabel }}</el-radio>
        </el-radio-group> 
      </el-form-item>
      <el-form-item label="性别" size="mini" prop="sex">
        <el-radio-group class="radioGroup" v-model="dataForm.sex">
          <el-radio class="radio" v-for="item in getDictList('gender')" :label="item.dictLabel"   :key="item.id" >{{item.dictLabel}}</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <el-form v-if="userId" 
      label-position="right"  label-width="80px"
      status-icon
      :inline="true"
      size="small"
      :model="AdataForm" :rules="AdataRule" ref="AdataForm"  @keydown.enter.native.prevent="dataFormSubmit()">
      <!-- el-form-item中prop属性必须要有才能找到需要验证的字段，另外prop需要与el-input中v-model的参数名称一致，否则会导致rules功能消失 -->
      <el-form-item label="账号" prop="username" >
        <el-input v-model="AdataForm.username" placeholder="登录帐号"></el-input>
      </el-form-item>
      
      <div v-show="state==3">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="AdataForm.name" placeholder="真实姓名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input show-password class="Aselect" v-model="AdataForm.password" type="password" placeholder="密码"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="comfirmPassword">
          <el-input show-password class="Aselect" v-model="AdataForm.comfirmPassword" type="password"
            placeholder="确认密码"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input  v-model="AdataForm.email" placeholder="邮箱"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="AdataForm.phone" placeholder="手机号"></el-input>
        </el-form-item>
        <el-form-item label="院系" prop="teaDepartment" size="mini">
          <el-select filterable class="Aselect" v-model="AdataForm.department" placeholder="院系">
            <el-option v-for="item in departmentDict" :label="item.dictLabel" :key="item.id"
              :value="item.dictLabel"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="性别" size="mini" prop="sex">
          <el-radio-group class="radioGroup" v-model="AdataForm.sex">
            <el-radio class="radio" v-for="item in getDictList('gender')" :label="item.dictLabel"
              :key="item.id">{{item.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>
      <div v-show="state==2">
        <el-form-item label="姓名" prop="teaName">
          <el-input  v-model="AdataForm.teaName" placeholder="真实姓名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input show-password class="Aselect" v-model="AdataForm.password" type="password" placeholder="密码"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="comfirmPassword">
          <el-input show-password class="Aselect" v-model="AdataForm.comfirmPassword" type="password"
            placeholder="确认密码"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="teaEmail">
          <el-input  v-model="AdataForm.teaEmail" placeholder="邮箱"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="teaPhone">
          <el-input  v-model="AdataForm.teaPhone" placeholder="手机号"></el-input>
        </el-form-item>
        <el-form-item label="学历" prop="teaRecord" size="mini">
          <el-select filterable class="Aselect" v-model="AdataForm.teaRecord" placeholder="学历">
            <el-option v-for="item in getDictList('degree')" :label="item.dictLabel" :key="item.id"
              :value="item.dictLabel"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="院系" prop="teaDepartment" size="mini">
          <el-select filterable class="Aselect" v-model="AdataForm.teaDepartment" placeholder="院系">
            <el-option v-for="item in departmentDict" :label="item.dictLabel" :key="item.id"
              :value="item.dictLabel"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="职称" prop="teaPost" size="mini">
          <el-select filterable class="Aselect" v-model="AdataForm.teaPost" placeholder="职称">
            <el-option v-for="item in getDictList('teacherTitle')" :key="item.id" :label="item.dictLabel"
              :value=" item.dictLabel"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="性别" size="small" prop="teaSex">
          <el-radio-group class="radioGroup" v-model="AdataForm.teaSex">
            <el-radio class="radio" v-for="item in getDictList('gender')" :label="item.dictLabel"
              :key="item.id">{{item.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>
      <div v-show="state==1">
        <el-form-item label="姓名" prop="stuName">
          <el-input  v-model="AdataForm.stuName" placeholder="真实姓名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input show-password class="Aselect" v-model="AdataForm.password" type="password" placeholder="密码"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="comfirmPassword">
          <el-input show-password class="Aselect" v-model="AdataForm.comfirmPassword" type="password"
            placeholder="确认密码"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="stuMail">
          <el-input  v-model="AdataForm.stuMail" placeholder="邮箱"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="stuPhone">
          <el-input   v-model="AdataForm.stuPhone" placeholder="手机号"></el-input>
        </el-form-item>
        <el-form-item label="院系" prop="stuDepartment" size="mini">
          <el-select filterable class="Aselect" v-model="AdataForm.stuDepartment" placeholder="院系">
            <el-option v-for="item in departmentDict" :label="item.dictLabel" :key="item.id"
              :value="item.dictLabel"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="专业" prop="stuProfessional" size="mini">
          <el-select filterable class="Aselect" v-model="AdataForm.stuProfessional" placeholder="专业">
            <el-option v-for="item in getDictList('major')" :label="item.dictLabel" :key="item.id"
              :value="item.dictLabel"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班级" prop="classes" size="mini">
          <el-select filterable class="Aselect" v-model="AdataForm.stuClass" placeholder="班级">
            <el-option v-for="item in getDictList('classes')" :label="item.dictLabel" :key="item.id"
              :value="item.dictLabel"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="QQ" prop="stuQq">
          <el-input v-model="AdataForm.stuQq" placeholder="QQ"></el-input>
        </el-form-item>
        <!-- <el-form-item label="微信" prop="stuWx">
          <el-input v-model="AdataForm.stuWx" placeholder="微信"></el-input>
        </el-form-item> -->
        <el-form-item label="课题" prop="stuTitle">
          <el-input v-model="AdataForm.stuTitle" placeholder="课题" disabled></el-input>
        </el-form-item>

        <el-form-item label="性别" size="mini" prop="sex">
          <el-radio-group class="radioGroup" v-model="AdataForm.stuSex">
            <el-radio class="radio" v-for="item in getDictList('gender')" :label="item.dictLabel" :key="item.id"
              :value="item.dictValue">{{item.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>
      
      <el-form-item label="状态" size="mini" prop="status">
        <el-radio-group  class="radioGroup"  v-model="AdataForm.status">
          <el-radio class="radio" :label="1">正常</el-radio>
          <el-radio class="radio" :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="身份" size="mini" prop="state">
        <el-radio-group  class="radioGroup" v-model="AdataForm.state" disabled>
          <el-radio class="radio" v-for="item in getDictList('role')" :key="item.dictLabel" :label="parseInt(item.dictValue)">{{
          item.dictLabel
          }}</el-radio>
        </el-radio-group> 
      </el-form-item>
    </el-form>


    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { isEmail, isMobile } from '@/utils/validate'
import servicesApi from '@/services/servicesApi';
import { getDictDataList } from '@/utils';
export default {
  data() {
    let validateComfirmPassword = (rule, value, callback) => {
      if (this.userId==0 && this.dataForm.password !== value) {
        callback(new Error('确认密码与密码输入不一致'))
      } else if (this.userId && this.AdataForm.password !== value) {
        callback(new Error('确认密码与密码输入不一致'))
      } else {
        callback()
      }
    }
    let validateEmail = (rule, value, callback) => {
      if (!isEmail(value)) {
        callback(new Error('邮箱格式错误'))
      } else {
        callback()
      }
    }
    let validateMobile = (rule, value, callback) => {
      if (!isMobile(value)) {
        callback(new Error('手机号格式错误'))
      } else {
        callback()
      }
    }
    let validateAccount = (rules, value, callback) => {
      if (!/[\u4E00-\u9FA5]/g.test(value)) {
        callback(new Error('请输入汉字姓名!'));
      }
      // else if (/^[0-9]+$/g.test(value)) {
      //     callback(new Error('账户名称不能输入纯数字!'));
      // } 
      else {
        callback();
      }

    }
    return {
      visible: false,
      state: 3,
      departmentDict: {},
      userId: 0,
      stateList: [
        { state: 3, stateName: '管理员' },
        { state: 2, stateName: '教师' },
        { state: 1, stateName: '学生' },
      ],
      dataForm: {//新增用户时
        username: '2020110228',
        name: '用户',
        password: 'Admin1234',
        comfirmPassword: 'Admin1234',
        department: '',
        email: '1927470557@qq.com',
        phone: '13982677074',
        state: 1,
        sex: '男',
        status: 1
      },
      AdataForm: {
        //用户表
        userId: 0,
        username: '2020110227',
        password: 'Admin1234',
        comfirmPassword: 'Admin1234',
        status: 0, //0:禁用,1正常
        state: 3, //用户角色 学生1 老师2 管理员3
        //管理员表
        phone: '13982677074',
        email: '1927470557@qq.com',
        name: '用户',
        sex: '男',
        wx: '',
        department: '',

        //学生表
        stuName: 'run',
        stuDepartment: '计算机科学',
        stuProfessional: '软件工程',
        stuPhone: '13982677074',
        stuMail: '1927470557@qq.com',
        stuClass: '2020级3班',
        stuSex: '男',
        stuWx: '',
        stuQq: '',
        stuTitle: '',
        
        //教师表
        teaSex: '男',
        teaWx: '',
        teaRecord: '硕士',
        teaPost: '教授',
        teaName: 'delete老师',
        teaPhone: '13982677074',
        teaDepartment: '计算机科学学院',
        teaEmail: '1927470557@qq.com',
      },
      dataRule: {
        username: [
          { required: true, message: '账号不能为空', trigger: 'blur' },
          { min: 4, max: 12, message: '长度在4-12位之间', trigger: 'blur' },
          { pattern: new RegExp('^(?=.*[a-zA-Z0-9].*).{4,12}$'), message: '密码为4-12位字母+数字组合，请重新输入', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '姓名不能为空', trigger: 'blur' },
          { min: 2, max: 8, message: '姓名长度为2-8,请重新输入', trigger: 'blur' },
          { validator: validateAccount, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          // { validator: validatePassword, trigger: 'blur' },
          { min: 6, max: 16, message: '长度在6-16位之间', trigger: 'blur' },
          { pattern: new RegExp('^(?=.*[0-9].*)(?=.*[A-Z].*)(?=.*[a-z].*).{6,16}$'), message: '密码为6-16位大小写字母+数字组合，请重新输入', trigger: 'blur' }
        ],
        comfirmPassword: [
          { required: true, message: '请输入确认密码', trigger: 'blur' },
          { validator: validateComfirmPassword, trigger: 'blur' },
          { min: 6, max: 16, message: '长度在6-16位之间', trigger: 'blur' },
          { pattern: new RegExp('^(?=.*[0-9].*)(?=.*[A-Z].*)(?=.*[a-z].*).{6,16}$'), message: '密码为6-16位大小写字母+数字组合，请重新输入', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { validator: validateEmail, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { validator: validateMobile, trigger: 'blur' }
        ]
      },
      AdataRule: {
        username: [
          { required: true, message: '账号不能为空', trigger: 'blur' },
          { min: 4, max: 12, message: '长度在4-12位之间', trigger: 'blur' },
          { pattern: new RegExp('^(?=.*[a-zA-Z0-9].*).{4,12}$'), message: '密码为4-12位字母+数字组合，请重新输入', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '姓名不能为空', trigger: 'blur' },
          { min: 2, max: 8, message: '姓名长度为2-8,请重新输入', trigger: 'blur' },
          { validator: validateAccount, trigger: 'blur' }
        ],
        teaName: [
          { required: true, message: '姓名不能为空', trigger: 'blur' },
          { min: 2, max: 8, message: '姓名长度为2-8,请重新输入', trigger: 'blur' },
          { validator: validateAccount, trigger: 'blur' }
        ],
        stuName: [
          { required: true, message: '姓名不能为空', trigger: 'blur' },
          { min: 2, max: 8, message: '姓名长度为2-8,请重新输入', trigger: 'blur' },
          { validator: validateAccount, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          // { validator: validatePassword, trigger: 'blur' },
          { min: 6, max: 16, message: '长度在6-16位之间', trigger: 'blur' },
          { pattern: new RegExp('^(?=.*[0-9].*)(?=.*[A-Z].*)(?=.*[a-z].*).{6,16}$'), message: '密码为6-16位大小写字母+数字组合', trigger: 'blur' }
        ],
        comfirmPassword: [
          { required: true, message: '请输入确认密码', trigger: 'blur' },
          { validator: validateComfirmPassword, trigger: 'blur' },
          { min: 6, max: 16, message: '长度在6-16位之间', trigger: 'blur' },
          { pattern: new RegExp('^(?=.*[0-9].*)(?=.*[A-Z].*)(?=.*[a-z].*).{6,16}$'), message: '密码为6-16位大小写字母+数字组合', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { validator: validateEmail, trigger: 'blur' }
        ],
        teaEmail: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { validator: validateEmail, trigger: 'blur' }
        ],
        stuMail: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { validator: validateEmail, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { validator: validateMobile, trigger: 'blur' }
        ],
        teaPhone: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { validator: validateMobile, trigger: 'blur' }
        ], 
        stuPhone: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { validator: validateMobile, trigger: 'blur' }
        ]

      }
    }
  },
  // watch: {
  //   userId(val) { // 函数名是要监听的属性
  //     // 重置表单，清空校验信息
  //     // console.log('监听的值=%s', val)
  //     this.$nextTick(() => {
  //        //  延时到下一帧才开始，也就是页面刚刚渲染结束！！
  //       if (this.$refs['dataForm'] != undefined) {
  //         this.$refs['dataForm'].resetFields()
  //       }
  //       if (this.$refs['AdataForm'] != undefined) {
  //         this.$refs['AdataForm'].resetFields()
  //       }
  //     })
  //   }
  // },
  methods: {
    getDictList(dictType) {
      let list = getDictDataList(dictType)
      // // console.log(list)
      return list
    },
    init(userId, state) {
      
      // console.log(userId)
      // console.log(state)
      this.userId = userId || 0 //高级语法
      this.state = state || 0
      let arrObj = window.SITE_CONFIG['dictList'].filter((item, index, arr) => { 
        // // console.log(item)
        return item.dictName == '院系' 
      })
      this.departmentDict = arrObj[0].dataList
      this.visible = true
      // 当数据被修改后使用这个方法，会回调获取更新后的dom再渲染出来
      this.$nextTick(() => {
        if (this.$refs['dataForm'] != undefined) {
          this.$refs['dataForm'].resetFields()
        }
        if (this.$refs['AdataForm'] != undefined) {
          this.$refs['AdataForm'].resetFields()
        }
      })

      if (this.userId) { //修改用户
        // console.log('修改用户')
        this.AdataForm.userId=this.userId
        this.AdataForm.state=this.state
        // // console.log(this.AdataForm)

        servicesApi.getUserById(this.userId).then(res => {
          let code = res.data.code
          let data = res.data.data
          // console.log('查询用户信息')
          if (code === 200) {
              this.AdataForm = { ...data }
              // console.log('AdataForm=%o', this.AdataForm)
          }
        })
      } else { //新增用户
        // console.log('新增用户')

      }
      
    },
    dataFormSubmit() {
      if (this.userId) {//修改
        this.$refs['AdataForm'].clearValidate() // 移除表单项的校验结果
        this.$refs['AdataForm'].validate((valid) => {
          if (!valid) { return false }
          if (this.state == 3) {
            servicesApi.updateUserA(this.AdataForm).then(res => {
              // console.log('管理员更新')
              let code = res.data.code
              let msg = res.data.msg
              if (code == 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')

                  }
                })
              } else {
                this.$message.error(msg)
              }
            })
          } else if (this.state == 2) {
            servicesApi.updateUserT(this.AdataForm).then(res => {
              // console.log('教师更新')
              let code = res.data.code
              let msg = res.data.msg
              if (code == 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')

                  }
                })
              } else {
                this.$message.error(msg)
              }
            })
          } else if (this.state == 1) {
            servicesApi.updateUserS(this.AdataForm).then(res => {
              // console.log('学生更新')
              let code = res.data.code
              let msg = res.data.msg
              if (code == 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')

                  }
                })
              } else {
                this.$message.error(msg)
              }
            })
          }
          
        })  
        
        
        
      } else { //新增
        this.$refs['dataForm'].clearValidate() // 移除表单项的校验结果
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            servicesApi.addUser(this.dataForm).then(res => {
              if (res.data.code === 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(res.data.msg)
              }
            })
          }

        })
      }
      
    }
  }
}
</script>
<style scoped>
.radioGroup{
  /* background-color: aqua; */
  width: 410px;
}
.radio{
  margin: 0px 10px;
  padding: 0px;
  width: 50px;
  /* background-color: rgb(145, 54, 54); */
}
.select{
  width: 159px;
  /* background-color: aquamarine; */
}
.Aselect {
  width: 169.667px;
  /* background-color: aquamarine; */
}

</style>
